package cloud.dwz.auth;

import cloud.dwz.tool.ToolJWT;
import io.wit.tool.ToolClient;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.resource.ResourceHttpRequestHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;

public final class AuthInterceptor implements HandlerInterceptor{

    @Override
    public boolean preHandle(final HttpServletRequest request,final HttpServletResponse response,final Object handler) throws Exception{
        if(handler instanceof ResourceHttpRequestHandler){return true;}
        final String uri = request.getRequestURI().substring(1);
        final boolean with = uri.startsWith("api/v");
        System.out.println(uri);
        if(with){
            final String token = request.getHeader("token");
            if(token == null || token.length() <= 0){
                ToolClient.responseJson(ToolClient.unauthorized(),response);
                return false;
            }else{
                try {
                    final HashMap<String,Object> userInfo = ToolJWT.getUserInfo(token);
                    final RequestMapping annotation = ((HandlerMethod)handler).getMethodAnnotation(RequestMapping.class);
                    final Long userId = (Long)userInfo.get("userId");
                    final Integer userType = (Integer)userInfo.get("userType");
                    final String name = annotation.name();
                    return true;
                } catch (final Exception e) {
                    ToolClient.responseJson(ToolClient.createJsonFail("token已过期,请重新登录!"),response);
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    public void postHandle(final HttpServletRequest httpServletRequest,final HttpServletResponse httpServletResponse,final Object o,final ModelAndView modelAndView) throws Exception{
    }

    @Override
    public void afterCompletion(final HttpServletRequest httpServletRequest,final HttpServletResponse httpServletResponse,final Object o,final Exception e) throws Exception{
    }
}